﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using ShopayServer.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PdfiumPrinter;

namespace ShopayServer.Controller
{
    public class Print : Base
    {
        public static PrintTemplate printTemplate = new PrintTemplate();

        public static Response CashBox(Request request, Response response)
        {
            try
            {
                printTemplate.CashBox(request.query("name"));
            }
            catch (Exception e)
            {
                return Error(response, "error");
            }

            return Message(response, "ok");
        }

        public static Response Template(Request request, Response response)
        {
            try
            {
                // 反射
                Type printer = printTemplate.GetType();

                foreach (JToken input in request.inputData)
                {
                    // 注入
                    MethodInfo methods = printer.GetMethod(input["a"].ToString());
                    // 参数组合
                    object[] parames = input["p"] == null ? null : input["p"].ToObject<List<object>>().ToArray();
                    // 执行
                    methods.Invoke(printTemplate, parames);
                }

                printTemplate.Print(request.query("name"));
            }
            catch (Exception e)
            {
                return Error(response, "error");
            }

            return Message(response, "ok");
        }

        public static Response Pdf(Request request, Response response)
        {
            try
            {
                PdfPrinter pdfPrinter = new PdfPrinter(request.query("name"));
                ;
                pdfPrinter.Print(request.input("file").ToString());
            }
            catch (Exception e)
            {
                return Error(response, "error");
            }

            return Message(response, "ok");
        }
    }
}
